package com.syl.generator.view.controller;

import com.syl.generator.common.bean.DatabaseBean;
import com.syl.generator.common.bean.TableColumnBean;
import com.syl.generator.common.constant.BaseConstant;
import com.syl.generator.common.dao.SqlLiteMapper;
import com.syl.generator.view.bean.GeneratorConfig;
import com.syl.generator.view.enums.FXMLPage;
import com.syl.generator.view.util.AlertUtil;
import com.syl.generator.view.util.UiBaseUtils;
import com.syl.generator.common.util.DbConnectionUtil;
import com.syl.generator.common.util.StringUtils;
import javafx.collections.ObservableList;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import org.apache.log4j.Logger;
import java.util.List;

/**
 * @author syl
 * @create 2018-04-01 14:07
 **/
public class LeftTreeNodeController extends TreeCell<TableColumnBean> {
    private static final Logger LOG = Logger.getLogger(LeftTreeNodeController.class);

    private TreeView<TableColumnBean> leftDBTree;
    private MainUIController main;

    public LeftTreeNodeController(TreeView<TableColumnBean> leftDBTree, MainUIController main){
        this.main = main;
        this.leftDBTree = leftDBTree;
        addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
            TreeItem<TableColumnBean> item = this.getTreeItem();
            if(item !=null){
                int level = leftDBTree.getTreeItemLevel(item);
                MouseButton button = event.getButton();
                int count = event.getClickCount();
                switch (level) {
                    case 1:
                        if(count == 2 && button == MouseButton.PRIMARY) loadDbTableNode(item,null);
                        else if(button == MouseButton.SECONDARY)openClidMenu(level);
                        break;
                    case 2:
                        LOG.info("点击:"+item.getValue());
                        if (count == 2  && button == MouseButton.PRIMARY) {//双击相应事件
                            dbclickHand(this, item);
                        }
                        if(count == 1 && button == MouseButton.SECONDARY){
                            dbclickHand(this, item);
                        }
                        break;
                }
            }
        });
    }

    private void openClidMenu(int level){
        TreeItem<TableColumnBean> item = this.getTreeItem();
        if(level == 1 && item.isExpanded())
            openChildMenu(this, item,true);
        else
            openChildMenu(this, item,false);
    }

    /** 双击响应事件处理
     * @param cell
     * @param treeItem
     */
    private void dbclickHand(TreeCell<TableColumnBean> cell, TreeItem<TableColumnBean> treeItem){
        if(treeItem == null){
            return;
        }
        String tableName = cell.getTreeItem().getValue().getTableName();
        ObservableList<TreeItem<TableColumnBean>> items = leftDBTree.getSelectionModel().getSelectedItems();

        TableColumnBean item = cell.getItem();
        main.getHideID().setText(item.getConfigID());
        main.getTableCommentField().setText(getTableCommentNames(items));
        main.getTableNameField().setText(getTableNames(items,false));
        main.getDomainObjectNameField().setText(getTableNames(items,true));
    }

    private String getTableCommentNames(ObservableList<TreeItem<TableColumnBean>> list){
        StringBuffer sb = new StringBuffer();
        list.forEach((TreeItem<TableColumnBean> item) ->{
            if(item !=null){
                TableColumnBean bean = item.getValue();
                String val = bean.getTableComment();
                sb.append(val);
                if(!StringUtils.isEmpty(val))sb.append(";");
            }
        });
        String str = sb.toString();
        if(str == null || str.isEmpty())return "";
        return str.substring(0, str.length()-1);
    }

    private String getTableNames(ObservableList<TreeItem<TableColumnBean>> list,boolean camel){
        StringBuffer sb = new StringBuffer();
        list.forEach((TreeItem<TableColumnBean> item) ->{
            if(item !=null){
                TableColumnBean bean = item.getValue();
                String val = bean.getTableName();
                sb.append(camel ? StringUtils.underlineToCamel(val,true) : val);
                sb.append(";");
            }
        });
        String str = sb.toString();
        if(str == null || str.isEmpty())return "";
        return str.substring(0, str.length()-1);
    }

    /** 初始化
     * @param treeItem
     * @param select
     */
    public void loadDbTableNode(TreeItem<TableColumnBean> treeItem, String select){
        DatabaseBean bean = (DatabaseBean)treeItem.getGraphic().getUserData();
        LOG.info(bean);
        try {
            List<TableColumnBean> columnList = DbConnectionUtil.getTableColumnList(bean,0);
            ObservableList<TreeItem<TableColumnBean>> children = treeItem.getChildren();
            children.clear();//初始化item
            for (TableColumnBean table:columnList){
                table.setConfigID(bean.getId());
                TreeItem<TableColumnBean> newTreeItem = new TreeItem<>();
                ImageView imageView = new ImageView(BaseConstant.TABLE_ICON);
                imageView.setFitHeight(16);
                imageView.setFitWidth(16);
                newTreeItem.setGraphic(imageView);
                newTreeItem.setValue(table);
                if(select == null)
                    children.add(newTreeItem);
                if(select !=null && table.getTableName().toLowerCase().indexOf(select.toLowerCase()) > -1)//搜索不忽略大小写
                    children.add(newTreeItem);
            }
            treeItem.setExpanded(true);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            AlertUtil.showErrorAlert("连接不上数据库");
        }
    }

    @Override
    public void updateItem(TableColumnBean item, boolean empty) {
        super.updateItem(item, empty);
        if (empty) {
            setText(null);
            setGraphic(null);
            return;
        }
        setText(item.getTableName());
        setGraphic(getTreeItem().getGraphic());
    }

    /** 打开子菜单
     * @param treeItem
     * @param swItch
     */
    private void openChildMenu(TreeCell<TableColumnBean> cell,TreeItem<TableColumnBean> treeItem,boolean swItch){
        final ContextMenu contextMenu = new ContextMenu();
        MenuItem item = new MenuItem("打开连接");
        item.setOnAction(event ->{
            loadDbTableNode(treeItem,null);
        });
        MenuItem item1 = new MenuItem("关闭连接");
        item1.setOnAction(event1 -> {
            treeItem.setExpanded(false);
            treeItem.getChildren().clear();
            main.setGeneratorConfigIntoUI(new GeneratorConfig());//初始化ui控件
        });
        MenuItem item2 = new MenuItem("编辑连接");
        item2.setOnAction(event1 -> {
              DatabaseBean bean = (DatabaseBean)treeItem.getGraphic().getUserData();
              DbConnectionController controller = (DbConnectionController)UiBaseUtils.openDialog(DbConnectionController.class,"编辑数据库连接", FXMLPage.NEW_CONNECTION,true);
              controller.setConfigToUI(bean);
              controller.setMainUIController(main);
        });
        MenuItem item3 = new MenuItem("删除连接");
        item3.setOnAction(event1 -> {
             DatabaseBean bean = (DatabaseBean)treeItem.getGraphic().getUserData();
             SqlLiteMapper dao = DbConnectionUtil.getSqliteDao();
            int i = dao.removeDbConnection(bean.getId());
            LOG.info("删除连接："+i);
            main.loadSchemaTreeNode();
        });
        contextMenu.getItems().addAll(swItch ? item1 : item, item2, item3);
        cell.setContextMenu(contextMenu);
    }

    private String getString() {
        return getItem() == null ? "" : getItem().toString();
    }
}
